package it.sciuto.qualeoperatore.adapters;

import it.sciuto.qualeoperatore.R;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

public class ContactsAdapter extends BaseAdapter {
	ArrayList<Contact> contacts;
	LayoutInflater mInflater;
	Activity activity;

	public ContactsAdapter(Activity activity, ArrayList<Contact> contacts) {
		this.contacts = contacts;
		this.mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.activity = activity;
	}

	@Override
	public int getCount() {
		return contacts.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup arg2) {
		convertView = mInflater.inflate(R.layout.contact_entry, null);
		convertView.setTag(position);
		ImageButton companyButton = (ImageButton) convertView.findViewById(R.id.company_entry);
		companyButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					Intent intent = new Intent(Intent.ACTION_CALL);
					String number = contacts.get(position).getNumber();
					if (number.charAt(0) == '+') {
						number = number.substring(3, number.length() - 1);
					}
					intent.setData(Uri.parse("tel:456" + number));
					activity.startActivity(intent);
				}
				catch (Exception e) {
					Log.e("QualeOperatore", "Failed to invoke call", e);
				}
			}
		});

		((TextView) convertView.findViewById(R.id.name_entry)).setText(contacts.get(position).getName());
		((TextView) convertView.findViewById(R.id.number_entry)).setText(contacts.get(position).getNumber());

		ImageButton call = (ImageButton) convertView.findViewById(R.id.send_call);
		call.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					Intent intent = new Intent(Intent.ACTION_CALL);
					intent.setData(Uri.parse("tel:" + contacts.get(position).getNumber()));
					activity.startActivity(intent);
				}
				catch (Exception e) {
					Log.e("QualeOperatore", "Failed to invoke call", e);
				}
			}
		});

		activity.registerForContextMenu(convertView);

		return convertView;
	}
}